package org.example.contestb.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import org.example.contestb.entity.DTO.StartDTO;
import org.example.contestb.entity.DTO.StopDTO;
import org.example.contestb.entity.MapData;
import org.example.contestb.entity.Message;
import org.example.contestb.responce.R;
import org.example.contestb.service.impl.MapTaskManager;
import org.example.contestb.config.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;
import org.example.contestb.Enum.ReturnCode;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/map")
//@CrossOrigin(origins = "*")
public class MapController {

    @Autowired
    private MapTaskManager mapTaskManager;

    /**
     * 测试WebSocket连接状态
     */
    @GetMapping("/ws-status")
    public R<Map<String, Object>> checkWebSocketStatus(@RequestParam String sessionId) {
        boolean isConnected = WebSocketServer.isConnected(sessionId);
        log.info("=== 检查WebSocket状态 === 会话ID: {}, 已连接: {}", sessionId, isConnected);
        
        Map<String, Object> data = new HashMap<>();
        data.put("sessionId", sessionId);
        data.put("connected", isConnected);
        data.put("onlineCount", WebSocketServer.getOnlineCount());
        
        return R.success(data);
    }

    /**
     * 启动定时获取数据任务
     * @param startDTO 包含会话ID和数据类型的DTO
     * @return 操作结果
     */
    @SaCheckLogin
    @PostMapping("/start")
    public R<Map<String, Object>> start(@RequestBody @Validated StartDTO startDTO) {
        String sessionId = startDTO.getSessionId();
        String type = startDTO.getType();
        String tableName = "tb_map_" + type;
        
        log.info("=== 请求启动任务 === 会话ID: {}, 类型: {}, 表名: {}", sessionId, type, tableName);
        
        // 先检查WebSocket连接状态
        boolean isConnected = WebSocketServer.isConnected(sessionId);
        
        if (!isConnected) {
            log.warn("=== WebSocket未连接 === 会话ID: {}, 无法启动任务", sessionId);
            Map<String, Object> errorData = new HashMap<>();
            errorData.put("sessionId", sessionId);
            errorData.put("connected", false);
            return R.error(ReturnCode.RC500.getCode(), "WebSocket连接未建立，请先建立WebSocket连接");
        }
        
        // 发送测试消息
        try {
            WebSocketServer.sendMessage(sessionId, "{\"type\":\"test\",\"message\":\"测试消息\"}");
        } catch (Exception e) {
            log.error("=== 发送测试消息失败 ===", e);
            return R.error(ReturnCode.RC500.getCode(), "WebSocket消息发送失败: " + e.getMessage());
        }
        
        // 启动任务
        mapTaskManager.startTask(sessionId, tableName);
        
        Map<String, Object> data = new HashMap<>();
        data.put("sessionId", sessionId);
        data.put("type", type);
        data.put("tableName", tableName);
        
        return R.success(data);
    }

    /**
     * 停止定时获取数据任务
     * @return 操作结果
     */
    @SaCheckLogin
    @PostMapping("/stop")
    public R<Map<String, Object>> stop(@RequestBody StopDTO stopDTO) {
        String sessionId = stopDTO.getSessionId();
        log.info("=== 请求停止任务 === 会话ID: {}", sessionId);
        
        mapTaskManager.stopTask(sessionId);
        
        Map<String, Object> data = new HashMap<>();
        data.put("sessionId", sessionId);
        
        return R.success(data);
    }

    @MessageMapping("/chat")
    @SendTo("/topic/messages")
    public MapData send(Message message) throws Exception {
        String time = new SimpleDateFormat("HH:mm").format(new Date());
        return new MapData();
    }
}
